﻿@using System.Text
@using System.Data;
@using ZoomLa.Common
@using ZoomLa.BLL
@using ZoomLa.Model
@using ZoomLa.Components
@using Newtonsoft.Json
@using Newtonsoft.Json.Linq
@model ZoomLaCMS.Models.Field.VM_FieldModel
@functions{
    private bool HasValue(DataRow dr,string name)
    {
        if (dr == null||!dr.Table.Columns.Contains(name)
            ||string.IsNullOrEmpty(DataConverter.CStr(dr[name]))) { return false; }
        return true;
    }
    public string ImagesCode()
    {
        string Name = Model.fieldMod.FieldName;
        DataRow dr = Model.valueDR;
        try
        {
            FieldModel model = new FieldModel(Model.fieldMod.Content);
            string tlp = "<ul data-id='txt_{0}' id=\"ul_{0}\" class=\"preview_img_ul\">{3}</ul>"
                        + "<div class=\"clearfix\"></div>"
                        + "<div><textarea id=\"txt_{0}\" name=\"txt_{0}\" class=\"form-control m715-50\" style=\"height: 110px\">{1}</textarea></div>"
                        + "<div class='btn-group' style=\"padding-left:0px;padding-top:2px;\"><input type='button' class='btn btn-primary' value='批量上传' onclick='UpFileDiag({2});' />"
                        + "<input type='button' class='btn btn-info' value='远程抓取' onclick='UpFileDiag({2}, \"/Plugins/WebUploader/RemoteImg.aspx\");'/>"
                        + "<input type='button' class='btn btn-info' value='图片库' onclick='SelectUppic({2});'/>"
                        + "<input type='button' class='btn btn-info' value='组图排序' onclick='SortImg({2})'"
                        + "</div>";
            string value = "", lis = "";
            string imgtlp = "<li class='margin_l5'><img src='{0}' class='preview_img'/><div class='file-panel' style='height: 0px;'><span class='cancel' title='删除'>删除</span><span class='editpic' title='编辑'>编辑</span></div></li>";
            if (HasValue(dr,Name))//有值
            {
                value = dr[Name].ToString().Trim(',');
                try
                {
                    value = "[" + value.TrimStart('[').TrimEnd(']').TrimEnd(',') + "]";
                    JArray arr = JsonConvert.DeserializeObject<JArray>(value);
                    foreach (JObject jobj in arr)
                    {
                        lis += string.Format(imgtlp, function.GetImgUrl(jobj["url"]));
                    }
                }
                catch (Exception ex) { lis = "<i style='color:red;'>(异常:非标准JSON格式," + ex.Message + ")</i>"; }
            }
            JObject obj = new JObject();
            obj.Add(new JProperty("field", "images"));//标识自己为组图字段
            obj.Add(new JProperty("nodeid", Model.NodeID));
            obj.Add(new JProperty("inputid", Name));
            obj.Add(new JProperty("name", Name));
            obj.Add(new JProperty("uploaddir", SiteConfig.SiteOption.UploadDir));
            obj.Add(new JProperty("iswater", model.GetValue("IsWater")));
            return string.Format(tlp, Name, value, JsonConvert.SerializeObject(obj), lis);
        }
        catch (Exception ex) { throw new Exception("组图字段" + Name + "出错,原因:" + ex.Message); }
    }
}
@{
    FieldModel fdmod = new FieldModel(Model.fieldMod.Content);
    int maxcount = DataConverter.CLng(fdmod.GetValue("maxcount"), 5);
    string name = Model.fieldMod.FieldName;
}
@if (fdmod.GetValue("type") == "mobile")
{
    <div>
        <div class="weui-cells weui-cells_form" id="uploader_@name" style="margin-top:0;">
            <div class="weui-cell">
                <div class="weui-cell__bd">
                    <div class="weui-uploader">
                        <div class="weui-uploader__hd">
                            <p class="weui-uploader__title">图片上传</p>
                            <div class="weui-uploader__info"><span id="uploadCount_@name">0</span>/@maxcount</div>
                        </div>
                        <div class="weui-uploader__bd">
                            <ul class="weui-uploader__files" id="uploaderFiles_@name"></ul>
                            <div class="weui-uploader__input-box">
                                <input id="uploaderInput" class="weui-uploader__input" type="file" accept="image/*" multiple="">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <input type="hidden" id="txt_@Model.fieldMod.FieldName" name="txt_@name" value="@Model.GetValue()" />
    </div>
    <link href="/dist/css/weui.min.css" rel="stylesheet" />
    <script src="/dist/js/weui.js?v=2"></script>
    <script>
        var a = function () {
            var mbup = { files: [], uploadCount: 0, field: "@name", $hid: $("#txt_@name"), maxcount: parseInt("@maxcount") };
            mbup.uploadCountDom = document.getElementById("uploadCount_@name");
            mbup.uploaderFiles = $("#uploaderFiles_@name");
            mbup.init = function () {
                // var data = [{ "url": "/UploadFiles/admin1/20161230/20161230aSBkCt.jpg", "desc": "" }, { "url": "/UploadFiles/admin1/20161230/20161230K6wslW.jpg", "desc": "" }];
                var data = [];
                if (mbup.$hid.val() == "") { return; }
                data = JSON.parse(mbup.$hid.val());
                for (var i = 0; i < data.length; i++) {
                    data[i].url=mbup.getImgUrl(data[i].url);
                }
                for (var i = 0; i < data.length; i++) {
                    mbup.files.push({ id: (i + 1), name: "" + i, url: data[i].url, imgurl: data[i].url });
                    var $item = $('<li class="weui-uploader__file" data-id="' + (i + 1) + '" style="background-image: url(' + data[i].url + ');"></li>');
                    mbup.uploaderFiles.append($item);
                    //----------------------------------
                }
                mbup.uploadCount = data.length;
                mbup.uploadCountDom.innerHTML = mbup.uploadCount;
            }
            mbup.del = function (id) {
                for (var i = 0; i < mbup.files.length; i++) {
                    if (mbup.files[i].id == id) { mbup.files.splice(i, 1); }
                }
                mbup.updateFileJson();
            }
            mbup.updateFileJson = function () {
                var list = [];
                var $hid = mbup.$hid;
                if (mbup.files.length < 1) { $hid.val(""); }
                for (var i = 0; i < mbup.files.length; i++) {
                    var file = mbup.files[i];
                    var model = { url: file.imgurl, desc: "" };
                    list.push(model);
                }
                $hid.val(JSON.stringify(list));
            }
            weui.uploader('#uploader_@name', {
                url: '/Plugins/Uploadify/UploadFileHandler.ashx',
                auto: true,
                type: 'file',
                fileVal: 'file',
                compress: {
                    width: 1600,
                    height: 1600,
                    quality: .8
                },
                onBeforeQueued: function onBeforeQueued(files) {
                    if (["image/jpg", "image/jpeg", "image/png", "image/gif"].indexOf(this.type) < 0) {
                        weui.alert('请上传图片');
                        return false;
                    }
                    if (this.size > 10 * 1024 * 1024) {
                        weui.alert('请上传不超过10M的图片');
                        return false;
                    }
                    if (files.length > mbup.maxcount) {
                        // 防止一下子选中过多文件
                        weui.alert('最多只能上传' + mbup.maxcount + '张图片，请重新选择');
                        return false;
                    }
                    if (mbup.uploadCount + 1 > mbup.maxcount) {
                        weui.alert('最多只能上传' + mbup.maxcount + '张图片');
                        return false;
                    }

                    ++mbup.uploadCount;
                    mbup.uploadCountDom.innerHTML = mbup.uploadCount;
                },
                //onQueued: function onQueued() {
                //    console.log(this);
                //},
                //onBeforeSend: function onBeforeSend(data, headers) {
                //    console.log(this, data, headers);
                //},
                //onProgress: function onProgress(procent) {
                //    console.log(this, procent);
                //},
                onSuccess: function onSuccess(ret) {
                    this.imgurl = ret;
                    mbup.files.push(this);
                    mbup.updateFileJson();
                },
                onError: function onError(err) {
                    console.log("failed", err);
                }
            });
            mbup.uploaderFiles[0].addEventListener('click', function (e) {
                var target = e.target;

                while (!target.classList.contains('weui-uploader__file') && target) {
                    target = target.parentNode;
                }
                if (!target) return;

                var url = target.getAttribute('style') || '';
                if (url) {
                    url = url.match(/url\((.*?)\)/)[1];
                }
                //上传完成后将图片转化为对象,并关联事件
                var gallery = weui.gallery(url, {
                    className: 'custom-name',
                    onDelete: function onDelete() {
                        weui.confirm('确定删除该图片？', function () {
                            --mbup.uploadCount;
                            mbup.uploadCountDom.innerHTML = mbup.uploadCount;
                            target.remove();
                            gallery.hide();
                            mbup.del($(target).data("id"));
                        });
                    }
                });
            });
            mbup.getImgUrl = function (url)
            {
                if(!url){return "";}
                url=url.toLocaleLowerCase();
                var updir = @SiteConfig.SiteOption.UploadDir.ToLower();
                if (url.indexOf("://") > 0)//不做处理
                {
 
                }
                else if (url.indexOf("uploadfiles/") != 0 && url.indexOf(updir) != 0)
                {
                    url = updir + url;
                }
                //url = "/" + url.TrimStart('/').Replace("//", "/");
                return url;
            }
            mbup.init();
        }();

    </script>
}
else
{
    @MvcHtmlString.Create(ImagesCode())
}


